using System.Text.RegularExpressions;
using AutoTest.Core.Infrastructure.Files;

namespace AutoTest.Core.Domain.TestFinding
{
    public class CSharpInspector : ICSharpInspector
    {
        private readonly IFileSystem _fileSystem;

        public CSharpInspector(IFileSystem fileSystem)
        {
            _fileSystem = fileSystem;
        }

        public string GetNamespace(string filename)
        {
            var text = _fileSystem.ReadAllText(filename);
            return GetFirstCaptureFrom(text, @"^[\s]*namespace[\s]*([0-9a-z._]*)");
        }

        public string GetFirstPublicClass(string filename)
        {
            var text = _fileSystem.ReadAllText(filename);
            return GetFirstCaptureFrom(text, @"^[\s]*public[ static ]*class[\s]*([0-9A-Z._]*)");
        }

        private static string GetFirstCaptureFrom(string text, string regex)
        {
            var regularExpression = new Regex(regex, RegexOptions.Multiline | RegexOptions.IgnoreCase);
            var match = regularExpression.Match(text);
            if (match == null || match.Groups.Count < 2)
                return "";
            var firstCapture = match.Groups[1].Value;
            return firstCapture.Trim();
        }
    }
}